<template>
<a-row>
  <a-button type="primary" @click="openSelectArea">指定可配送区域和运费</a-button>
  <a-table
    v-if="dataSource && dataSource.length"
    rowKey="areaCodes"
    :columns="columns"
    :data-source="dataSource"
    :pagination="false"
  ></a-table>
  
  <a-modal 
    :visible="selectAreaVisible"
    okText="提交"
    class="delivery-select-area"
    cancelText="关闭"
    title="选择配送区域"
    :maskClosable="false"
    :keyboard="false"
    width="800px"
    @cancel="closeArea()"
    @ok="handleSubmit">
    <a-spin :spinning="loadingArea" tip="正在获取区域信息，请稍后...">
      <custom-checkbox :options="areaOptions" v-model="selectedArea" />
    </a-spin>
  </a-modal>
</a-row>
</template>
<script>
import {getAreaTree} from '@/utils/asyncUtils'
import CustomCheckbox from '@/components/form/CustomCheckbox'

export default {
  name: 'delivery-area',
  components: {
    CustomCheckbox
  },
  props: {
    costType: {
      type: Number,
      required: true
    },
    value: {
      type: Array,
    },
  },
  computed: {
    columns () {
      const that = this
      const columns =  [
        {title: '可配送区域',dataIndex: 'areaName', ellipsis: true, width: 250},
        {title: '首件(个)',dataIndex: 'firstNumber', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={0} v-model={record['firstNumber']}  />},
        {title: '运费(元)',dataIndex: 'firstPrice', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={2} v-model={record['firstPrice']} />},
        {title: '续件(个)',dataIndex: 'followNumber', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={0} v-model={record['followNumber']}  />},
        {title: '续费(元)',dataIndex: 'followPrice', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={2} v-model={record['followPrice']}   />},
        {title: '操作',dataIndex: 'operation',customRender: that.operation},
      ]
      if (this.costType === 2) {
        columns.splice(1, 1, {title: '首重(kg)',dataIndex: 'firstWeight', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={2} v-model={record['firstWeight']}  />})
        columns.splice(3, 1, {title: '续重(kg)',dataIndex: 'followWeight', customRender: (text, record) => <a-input-number onChange={()=>this.valueChange()} min={0} precision={2} v-model={record['followWeight']}  />})
      }
      return columns
    }
  },
  watch: {
    value: {
      immediate: true,
      handler (newVal) {
        this.dataSource = newVal || []
      }
    }
  },
  data () {
    return {
      selectedArea: '',
      selectAreaVisible: false,
      dataSource: [],
      areaOptions: [],
      loadingArea: false,
      currentRecord: null
    }
  },
  methods: {
    operation (text, record, index) {
      return (<span class="nowrap">
        <span class="text-primary pointer" onClick={()=>this.modifyRow(record, index)}>修改</span>
        <a-divider type="vertical" />
        <span class="text-danger pointer" onClick={()=>this.deleteRows(index)}>删除</span>
      </span>)
    },
    // 当值发生变化时提交
    valueChange () {
      this.$emit('change', this.dataSource)
    },
    // 删除一行
    deleteRows (index) {
      this.dataSource.splice(index, 1)
      this.valueChange()
    },
    getCanArea(data,selected,labels=[]){
      data.forEach(item=>{
        if(selected.indexOf(item.id)>-1){
          labels.push(item.areaName);
        }
        if(item.children && item.children.length>0){
          this.getCanArea(item.children,selected, labels);
        }
      });
      return labels;
    },
    // 选择区域后提交
    handleSubmit () {
      if (!this.selectedArea.length) {
        this.$message.error('请至少选择一项再提交！')
        return 
      }
      console.log('this.selectedArea',this.selectedArea);
      console.log('this.areaOptions',this.areaOptions);
      const selected = this.selectedArea.split(',')
      console.log('selected',selected);
      // const areaName = this.areaOptions.filter(item => {
      //   return selected.indexOf(item.value) > -1
      // }).map(item => item.label).join(',')

      const areaName=this.getCanArea(this.areaOptions,selected).join(',');
      console.log('areaName',areaName);

      if (this.currentRecord) {
        this.currentRecord.areaCodes = this.selectedArea
        this.currentRecord.areaName = areaName
      } else {
        this.dataSource.push({
          areaCodes: this.selectedArea,
          areaName,
          firstNumber: 0,
          firstWeight: 0,
          firstPrice: 0,
          followNumber: 0,
          followWeight: 0,
          followPrice: 0
        });
      }
      this.valueChange()
      this.closeArea()
    },
    closeArea () {
      this.selectAreaVisible = false
      this.loadingArea = false
      this.selectedArea = ''
      this.currentRecord = null

    },
    setDiabled(data,keys){
      data.forEach(item=>{
        item.disabled=keys.indexOf(item.id) > -1;
        if(item.children && item.children.length>0){
          this.setDiabled(item.children,keys);
        }
      })
      return data;
    },
    setToArea(data){
      data.forEach(item=>{
        if(item.children && item.children.length>0){
          item.children.forEach(item2=>{
            if(item2.areaName.substr(item2.areaName.length-1)=='区'){
              item2.children=null;
            }
            else {
              if(item2.children && item2.children.length>0){
                item2.children.forEach(item3=>{
                  item3.children=null;
                })
              }
            }
          })
        }
      })
      return data;
    },
    // 打开选择区域弹窗
    openSelectArea () {
      const disabledAreas = []
      this.dataSource.forEach(item => {
        const areaCodes = item.areaCodes.split(',')
        disabledAreas.push(...areaCodes)
      })
      this.loadingArea = true
      getAreaTree().then(res => {
        this.loadingArea = false
        let tmpData=this.setDiabled(res,disabledAreas);
        tmpData=this.setToArea(tmpData);
        this.areaOptions=tmpData
        // this.areaOptions = res.map(item => ({
        //   label: item.areaName,
        //   value: item.id,
        //   disabled: disabledAreas.indexOf(item.id) > -1
        // }))
        console.log('getAreaTree()',res);
      })
      this.selectAreaVisible = true
    },

    // 修改区域
    modifyRow (record, rowIndex) {
      this.currentRecord = record
      this.selectedArea = record.areaCodes
      const disabledAreas = []
      this.dataSource.forEach((item, index) => {
        if (rowIndex !== index) {
          const areaCodes = item.areaCodes.split(',')
          disabledAreas.push(...areaCodes)
        }
      })
      this.loadingArea = true
      getAreaTree().then(res => {
        this.loadingArea = false
        
        let tmpData=this.setDiabled(res,disabledAreas);
        tmpData=this.setToArea(tmpData);
        this.areaOptions=tmpData

        // this.areaOptions = res.map(item => ({
        //   label: item.areaName,
        //   value: item.id,
        //   disabled: disabledAreas.indexOf(item.id) > -1
        // }))
      })
      this.selectAreaVisible = true
    },
  }
}
</script>
<style lang="less">
  .delivery-select-area {
    .ant-checkbox-group {
      display: grid;
      grid-template-columns: 25% 25% 25% 25%;
    }
  }
</style>